package com.nts.pmchelperdemo3.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nts.pmchelperdemo3.constant.MessageConstant;
import com.nts.pmchelperdemo3.constant.OrderStatusConstant;
import com.nts.pmchelperdemo3.dto.OrderDTO;
import com.nts.pmchelperdemo3.entity.Order;
import com.nts.pmchelperdemo3.entity.Tool;
import com.nts.pmchelperdemo3.exception.*;
import com.nts.pmchelperdemo3.mapper.OrderMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nts.pmchelperdemo3.result.Result;
import com.nts.pmchelperdemo3.service.OrderService;
import com.nts.pmchelperdemo3.service.SchedulingService;
import com.nts.pmchelperdemo3.service.ToolService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ToolService toolService;

    @Autowired
    private SchedulingService schedulingService;

    @Override
    @Transactional
    public OrderDTO createOrder(OrderDTO orderDTO){
        //校验订单函数
        if (orderDTO.getToolQuantity() <= 0){
            //ResultUtil.throwException("刀具数量必须大于0");
            throw new ToolNullException(MessageConstant.TOOL_NUMBER_IS_NULL);
        }
        if (orderDTO.getEndTime().isBefore(orderDTO.getStartTime())){
            //ResultUtil.throwException("截止日期不能早于开始日期");
            throw new DeadlineEarlyException(MessageConstant.DEADLINE_TIME_TOO_EARLY);
        }

        //区分普通刀与定制刀
        Tool tool = toolService.getToolByName(orderDTO.getToolName());
        Order order = new Order();

        BeanUtils.copyProperties(orderDTO,order);

        if (tool != null && tool.getType().equals(0)){
            order.setStatus(0);
        }else{
            //非普通刀，即定制刀
            if (orderDTO.getCustomSharpenTime() == null || orderDTO.getCustomCoatTime() == null){
                //throw new ToolNotFoundException("未查询到该普通刀，请输入定制刀的磨刀和涂层时间");
                throw new ToolNotFoundException(MessageConstant.TOOL_NOT_FOUND);
            }
            order.setStatus(0);
            order.setCustomSharpenTime(orderDTO.getCustomSharpenTime());
            order.setCustomCoatTime(orderDTO.getCustomCoatTime());

        }
        orderMapper.insert(order);
        orderDTO.setId(order.getId());

        try {
            // 调用排班生成方法，任务类型为0（磨刀）
            schedulingService.generateScheduling(order.getId(), 0);
        } catch (Exception e) {
            // 处理异常（如机器不足等），可根据业务需求决定是否回滚订单
            throw new RuntimeException("订单创建成功，但磨刀排班生成失败：" + e.getMessage());
        }
        return orderDTO;
    }

    @Override
    public List<OrderDTO>queryOrders(Integer status,Integer page,Integer size){
        Page<Order> pageQuery = new Page<>(page,size);
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        if (status != null){
            queryWrapper.eq("status",status);
        }
        queryWrapper.orderByDesc("priority").orderByAsc("end_time");

        IPage<Order> orderPage = orderMapper.selectPage(pageQuery,queryWrapper);
        return orderPage.getRecords().stream().map(this::convertToDTO).collect(Collectors.toList());

    }

    @Override
    public OrderDTO getOrderById(Long id){
        Order order = orderMapper.selectById(id);
        if (order == null){
            throw new OrderNotFoundException(MessageConstant.ORDER_NOT_FOUND);
            //ResultUtil.throwException("订单不存在");
        }
        return convertToDTO(order);
    }

    @Override
    @Transactional
    public OrderDTO updateOrderStatus(Long id,Integer newStatus){
        Order order = orderMapper.selectById(id);
        if (order == null){
            throw new OrderNotFoundException(MessageConstant.ORDER_NOT_FOUND);
            //ResultUtil.throwException("订单不存在");
        }
        //状态流转规则
        //Integer currentStatus = order.getStatus();
        List<Integer>allowedStatuses = OrderStatusConstant.VALID_TRANSITIONS.get(order.getStatus());
        if (allowedStatuses == null || !allowedStatuses.contains(newStatus)){
            throw new TransitionErrorException(MessageConstant.TRANSITION_ERROR);
            //ResultUtil.throwException("不支持的状态流转(当前;" + currentStatus + ",目标:" +newStatus + ")");
        }
        //更新状态
        order.setStatus(newStatus);
        orderMapper.updateById(order);
        return convertToDTO(order);
    }

    @Override
    @Transactional
    public void deleteOrder(Long id){
        Order order = orderMapper.selectById(id);
        if(order == null){
            throw new OrderNotFoundException(MessageConstant.ORDER_NOT_FOUND);
            //ResultUtil.throwException("订单不存在");
        }
        if (order.getStatus() != 0)
        {
            throw new OrderWorkingException(MessageConstant.ORDER_IS_WORKING);
            //ResultUtil.throwException("仅接单中状态的订单可删除");
        }
        orderMapper.deleteById(id);
    }

    @Override
    public int countOrderByStatus(Integer status){
        QueryWrapper<Order>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",status);

        return orderMapper.selectCount(queryWrapper);
    }


    @Override
    public List<OrderDTO> getOrderByStatus(Integer status){
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",status);
        List<Order>orders = orderMapper.selectList(queryWrapper);
        return orders.stream().map(this::convertToDTO).collect(Collectors.toList());

    }



    //转DTO
    private OrderDTO convertToDTO(Order order)
    {
        OrderDTO dto = new OrderDTO();
        BeanUtils.copyProperties(order,dto);
        return dto;
    }

}
